package com.mezz.bones.framework.web.filter;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: zhuang
 * @Date: 2024/7/12 17:40
 * @Description: 统一请求跟踪ID 可根据此数值去查询 此请求下的 所有日志信息
 * @Version: 1.0
 **/

@Component
public class MdcFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            // Generate a unique ID
            String requestId = getRequestId(servletRequest);
            MDC.put("requestId", requestId); // Put unique ID in MDC

            filterChain.doFilter(servletRequest, servletResponse); // Continue the filter chain

            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setHeader("Request-Id", requestId);
        } finally {
            MDC.clear(); // Clear the MDC after processing
        }
    }

    private String getRequestId(ServletRequest request) {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestId = httpRequest.getHeader("Request-Id");

        if (StrUtil.isBlank(requestId)) {
            //如果前端没传 则自定义
            requestId = UUID.randomUUID().toString();
        }

        return requestId;
    }
}
